<!--  -->
<template>
  <div class="">
    <el-tree
      :data="menu"
      :props="menuProps"
      @node-click="handleNodeClick"
      node-key="catId"
      show-checkbox
      :default-expanded-keys="expanded_keys"
      :expand-on-click-node="false"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level != 3"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button
            v-if="data.children.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      title="提示"
      :visible.sync="addnodeVisible"
      width="30%"
      :before-close="handleClose"
    >
      <div>
        <el-form
          :model="nodeItem"
          status-icon

          ref="nodeItems"
          label-width="100px"
        >
          <el-form-item label="名称" >
            <el-input
              prop="name"
              type="input"
              v-model="nodeItem.name"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="addNodeItem('nodeItems')">提交</el-button>
            <el-button @click="resetNodeItemForm('nodeItems')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 这里存放数据
    return {
      expanded_keys: [],
      addnodeVisible: false,
      menu: [],
      menuProps: {
        children: "children",
        label: "name",
      },
      nodeItem:{
        name:'',
        parentCid:0,
        catLevel:0,
        showStatus:1,
        sort:0
      }
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    addNodeItem(form){
  this.$http({
            url: this.$http.adornUrl("/product/category/save"),
            method: "post",
            data: this.$http.adornData(this.nodeItem, false),
          }).then(res=>{
            // console.log(res)
            this.$message({
                type: "success",
                message: "添加成功!",
              });
              this.getDataList()
              this.expanded_keys = [this.nodeItem.parentCid];
              this.addnodeVisible=false
              this.$refs[form].resetFields()
          }).catch(res=>{
            this.$message({
                type: "error",
                message: "添加失败!",
              });
              console.log(res)
          })
    },
    resetNodeItemForm(form){
      this.$refs[form].resetFields()
    },
    handleNodeClick(data) {
      // console.log(data);
    },
    getDataList() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log(data);
        if (data.code == 0) {
          this.menu = data.page;
        }
      });
    },
    append(data) {

      this.nodeItem.catLevel=data.catLevel+1
      this.nodeItem.parentCid=data.catId
      this.addnodeVisible = true;
      console.log(this.nodeItem,data);
    },
    remove(node, data) {
      var ids = [data.catId];
      this.$confirm(`是否删除【${data.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          })
            .then((res) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getDataList();
              console.log(node);
              this.expanded_keys = [node.parent.data.catId];
            })
            .catch((e) => {
              this.$message({
                type: "error",
                message: e,
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
           this.$refs['nodeItems'].resetFields();
          done();

        })
        .catch((_) => {});
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getDataList();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
/* //@import url(); 引入公共css类 */
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
